package com.xiaolei.fastnio.library.Executors

import java.util.concurrent.*
import java.util.concurrent.ThreadPoolExecutor.AbortPolicy
import java.util.concurrent.atomic.AtomicInteger

/**
 * 手动设置线程池
 */
object ExecutorServices
{
    private val defaultHandler = AbortPolicy()

    /**
     * 创建线程池的方法
     * @param count 线程数
     * @param capacity 同时处理任务数
     * @param groupName 线程池的名称
     */
    fun newFixedThreadPool(count: Int, capacity: Int= Int.MAX_VALUE, groupName: String): ExecutorService
    {
        return ThreadPoolExecutor(count,
                count,
                0L,
                TimeUnit.MILLISECONDS,
                LinkedBlockingQueue<Runnable>(capacity),
                SimpleThreadFactory(groupName),
                defaultHandler
        )
    }

    private class SimpleThreadFactory(private val groupName: String) : ThreadFactory
    {
        private var group: ThreadGroup
        private var threadNumber = AtomicInteger(1)

        init
        {
            val s = System.getSecurityManager()
            group = if (s != null) s.threadGroup else Thread.currentThread().threadGroup
        }

        override fun newThread(r: Runnable): Thread
        {
            val t = Thread(group, r, "$groupName-${threadNumber.getAndIncrement()}", 0)
            if (t.isDaemon)
                t.isDaemon = false
            if (t.priority != Thread.NORM_PRIORITY)
                t.priority = Thread.NORM_PRIORITY
            return t
        }
    }
}